<?php


namespace App\Extensions;

use Encore\Admin\Actions\RowAction;

class LayerRowAction extends RowAction
{
    protected $title;
    protected $href;
    protected $width;
    protected $height;

    public function __construct($href, $name, $width = '1000', $height = '800')
    {
        $this->name = $name;
        if ($href instanceof \Closure) {
            $callback = $href->bindTo($this);
            $this->href = call_user_func_array($callback, [$this]);
        } else {
            $this->href = $href;
        }
        $this->width = is_numeric($width) ? $width : '';
        $this->height = is_numeric($height) ? $height : '';
        parent::__construct();
    }

    public function name(): string
    {
        return <<<HTML
    &nbsp;{$this->name}
HTML;
    }

    public function title(): string
    {
        return $this->title ?: $this->name;
    }

    public function __toString()
    {
        return $this->render();
    }

    public function render(): string
    {
        if (!$this->width && !$this->height) {
            return $this->layerFullRender();
        }
        return $this->layerShowRender();
    }

    protected function layerFullRender()
    {
        return <<<EOT
<a style="white-space:nowrap;" href="javascript:;" onclick="layer_full('{$this->title()}','{$this->href}')">
    {$this->name}
</a>
EOT;
    }

    protected function layerShowRender()
    {
        return <<<EOT
<a style="white-space:nowrap;" href="javascript:;" onclick="layer_show('{$this->title()}','{$this->href}','{$this->width}','{$this->height}')">
{$this->name}
</a>
EOT;
    }

}
